package com.lzkj.baotouhousingfund.http;


import com.lzkj.baotouhousingfund.http.exception.ApiException;
import com.lzkj.baotouhousingfund.http.response.HttpResponse;

import io.reactivex.FlowableTransformer;
import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.ObservableTransformer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

/**
 * @author Chengs
 * @ClassName: RxUtil
 * @Description: 请求工具类
 * @date 2018/3/8 16:52
 */
public class RxUtil {

    /**
     * 统一线程处理
     *
     * @param <T>
     * @return
     */
    public static <T> ObservableTransformer<T, T> rxSchedulerHelper() {
        //compose简化线程
        return upstream -> upstream.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());
    }

    public static <T> FlowableTransformer<T, T> rxFlowableSchedulerHelper() {
        //compose简化线程
        return upstream -> upstream.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());
    }


    /**
     * 统一返回结果处理
     *
     * @param <T>
     * @return
     */
    public static <T> ObservableTransformer<HttpResponse<T>, T> handleWXResult() {
        //compose判断结果
        return upstream -> upstream.flatMap((Function<HttpResponse<T>, ObservableSource<T>>)
                tHttpResponse -> {
                    if (tHttpResponse.getCode() == 200) {
                        return createData(tHttpResponse.getNewslist());
                    } else {
                        return Observable.error(new ApiException("服务器返回error"));
                    }
                });
    }

    /**
     * 生成Observable
     *
     * @param <T>
     * @return
     */
    public static <T> Observable<T> createData(final T t) {
        return Observable.create(subscriber -> {
            try {
                subscriber.onNext(t);
                subscriber.onComplete();
            } catch (Exception e) {
                subscriber.onError(e);
            }
        });
    }
}
